package cn.dada.dadarecipes.mall.cart.service.Impl;

import cn.dada.dadarecipes.base.enums.OrderStatus;
import cn.dada.dadarecipes.base.enums.ShippingStatus;
import cn.dada.dadarecipes.base.exception.ServiceException;
import cn.dada.dadarecipes.base.response.StatusCode;
import cn.dada.dadarecipes.mall.cart.mapper.CartMapper;
import cn.dada.dadarecipes.mall.cart.pojo.dto.CartAddParam;
import cn.dada.dadarecipes.mall.cart.pojo.dto.CartDeleteParam;
import cn.dada.dadarecipes.mall.cart.pojo.dto.CartUpdateParam;
import cn.dada.dadarecipes.mall.cart.pojo.dto.OrderAddDTO;
import cn.dada.dadarecipes.mall.cart.pojo.entity.Cart;
import cn.dada.dadarecipes.mall.cart.pojo.entity.CartProducts;
import cn.dada.dadarecipes.mall.cart.pojo.vo.CartProductVO;
import cn.dada.dadarecipes.mall.cart.service.CartService;
import cn.dada.dadarecipes.mall.product.mapper.ProductMapper;
import cn.dada.dadarecipes.mall.product.pojo.dto.ProductQuery;
import cn.dada.dadarecipes.mall.product.pojo.vo.ProductVO;
import cn.dada.dadarecipes.mall.shop.mapper.ShopMapper;
import cn.dada.dadarecipes.mall.shop.pojo.vo.ShopVO;
import cn.dada.dadarecipes.user.order.mapper.OrderMapper;
import cn.dada.dadarecipes.user.order.pojo.entity.Order;
import cn.dada.dadarecipes.user.shipping_address.mapper.ShippingAddressMapper;
import cn.dada.dadarecipes.user.shipping_address.pojo.vo.ShippingAddressVO;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    CartMapper cartMapper;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    ShippingAddressMapper shippingAddressMapper;

    @Autowired
    ShopMapper shopMapper;

    @Autowired
    OrderMapper ordersMapper;

    /**
     *获取购物车列表业务
     * @param userId
     * @return
     */
    @Override
    public List<CartProductVO> selectCart(Long userId) {
        log.debug("获取购物车列表业务,userId={}",userId);
        Cart cart = getCart(userId);
        if(cart == null){
            throw new ServiceException(StatusCode.CART_IS_EMPTY);
        }
        List<CartProductVO> list = cartMapper.selectCart(cart.getId());
        return list;
    }

    /**
     *添加商品到购物车业务
     * @param cartAddParam
     */
    @Override
    public void addProducts(CartAddParam cartAddParam) {
        log.debug("添加商品到购物车业务,cartAddParam={}",cartAddParam);
        //根据商品id查询商品信息
        List<ProductVO> productVOS = getProductVOS(cartAddParam.getProductId());

        //根据用户id查询购物车是否存在或购物车是否为空
        Cart cart = getCart(cartAddParam.getUserId());
        //1.购物车不存在或者购物车为空，则新建购物车
        if(cart == null){
            Cart cart1 = new Cart();
            cart1.setUserId(cartAddParam.getUserId());
            cart1.setCreateTime(new Date());
            cartMapper.insert(cart1);
            log.debug("新建购物车成功，购物车id为：" + cart1.getId());
            cart = cart1;
            //添加商品到购物车里
            CartProducts cartProducts = new CartProducts();
            BeanUtils.copyProperties(cartAddParam, cartProducts);
            cartProducts.setCartId(cart.getId());
            cartProducts.setShopId(productVOS.get(0).getShopId());
            cartProducts.setProductId(cartAddParam.getProductId());
            cartProducts.setPrice(productVOS.get(0).getPrice());
            cartProducts.setQuantity(cartAddParam.getQuantity());
            cartProducts.setStatus("0");
            cartProducts.setAddedTime(new Date());
            cartMapper.addProducts(cartProducts);
        } else {
            //2.购物车已存在且不为空
            log.debug("购物车存在，查询购物车内是否有商品");
            //根据用户id查询购物车信息
            Cart cart1 = cartMapper.selectCartByUserId(cartAddParam.getUserId());
            //查询购物车列表
            List<CartProductVO> cartVOS = cartMapper.selectCart(cart1.getId());
            log.debug("购物车列表为：" + cartVOS);
            boolean flag = true;
            for (CartProductVO cartVO : cartVOS) {
                System.out.println("cartAddParam:"+cartAddParam.getProductId());
                log.debug("商品id为：" + cartVO.getProductId());
                //对比商品id是否相同，如果商品id相同则更新数量
                if (cartVO.getProductId().equals(cartAddParam.getProductId())) {
                    System.out.println("hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh");

                    //商品id相同，购物车存在，则更新改用户相同商品的数量
                    CartUpdateParam cartUpdateParam = new CartUpdateParam();
                    cartUpdateParam.setUserId(cartAddParam.getUserId());
                    cartUpdateParam.setProductId(cartVO.getProductId());
                    cartUpdateParam.setQuantity(cartAddParam.getQuantity()+cartVO.getQuantity());
                    //更新购物车商品信息
                    updateCartProducts(cartUpdateParam);
                    //更新购物车
                    cart.setUpdateTime(new Date());
                    cartMapper.update(cart);
                    flag = false;
                    break;
                }
            }
            if(flag){
                log.debug("购物车不存在相同商品，添加商品");
                CartProducts cartProducts = new CartProducts();
                BeanUtils.copyProperties(cartAddParam, cartProducts);
                cartProducts.setCartId(cart1.getId());
                cartProducts.setShopId(productVOS.get(0).getShopId());
                cartProducts.setProductId(cartAddParam.getProductId());
                cartProducts.setPrice(productVOS.get(0).getPrice());
                cartProducts.setStatus("0");
                cartProducts.setAddedTime(new Date());
                //添加商品到购物车里
                cartMapper.addProducts(cartProducts);
                //更新购物车
                cart.setUpdateTime(new Date());
                cartMapper.update(cart);
            }
        }
    }


    /**
     * 查询商品信息
     * @param productId
     * @return
     */
    private List<ProductVO> getProductVOS(Long productId) {
        //通过id查询商品信息
        ProductQuery productQuery = new ProductQuery();
        productQuery.setId(productId);
        List<ProductVO> productVOS = productMapper.selectProduct(productQuery);
        log.debug("商品信息为：" + productVOS);
        return productVOS;
    }

    /**
     * 更新购物车商品信息业务
     * @param cartUpdateParam
     */
    @Override
    public void updateCartProducts(CartUpdateParam cartUpdateParam) {
        log.debug("更新购物车商品数量业务,cartUpdateParam={}",cartUpdateParam);
        //更新购物车商品信息
        //通过用户id查询购物车id
        Cart cart = getCart(cartUpdateParam.getUserId());
        //查询购物车商品列表
        List<CartProductVO> cartProductVOS = cartMapper.selectCart(cart.getId());
        //遍历购物车列表
        for (CartProductVO cartProductVO : cartProductVOS){
            //对比商品id
            if (cartProductVO.getProductId().equals(cartUpdateParam.getProductId())){
                log.debug("购物车存在相同商品，商品原来的数量" + cartProductVO.getQuantity());
                CartProducts cartProducts = new CartProducts();
                //设置购物车商品表的购物车id
                cartProducts.setCartId(cart.getId());
                cartProducts.setProductId(cartProductVO.getProductId());
                cartProducts.setQuantity(cartUpdateParam.getQuantity());
                cartProducts.setStatus(cartUpdateParam.getStatus());
                cartProducts.setAddedTime(new Date());
                cartMapper.updateCartProducts(cartProducts);
            }
        }
    }

    /**
     * 删除购物车商品业务
     * @param
     */

    @Override
    public void deleteProducts(CartDeleteParam cartDeleteParam) {
        log.debug("删除购物车商品业务,cartDeleteParam={}",cartDeleteParam);
        //获取购物车信息
        Cart cart = getCart(cartDeleteParam.getUserId());
        CartDeleteParam cartDeleteParam1 = new CartDeleteParam();
        cartDeleteParam1.setCartId(cart.getId());
        cartDeleteParam1.setProductId(cartDeleteParam.getProductId());
        cartMapper.deleteCartProducts(cartDeleteParam1);
        //查询购物车商品列表
        List<CartProductVO> cartProductVOS = cartMapper.selectCart(cart.getId());
        if(cartProductVOS.size() == 0){
            log.debug("购物车为空，删除购物车");
            cartMapper.deleteCart(cartDeleteParam.getUserId());
        }
    }

    /**
     * 新增订单业务
     * @param orderAddDTO
     */
    @Override
    public void addOrder(OrderAddDTO orderAddDTO) {
        Long userId = orderAddDTO.getUserId();
        log.debug("新增订单,userId={}", userId);
        //查询地址
       ShippingAddressVO shippingAddressVO
               = shippingAddressMapper.selectShippingAddressByAddressId(orderAddDTO.getShippingAddressId());

        //获取购物车信息
        Cart cart = getCart(userId);
        log.debug("购物车信息为：" + cart);
        //查询购物车商品信息
        List<CartProductVO> cartProductVOS = cartMapper.selectCart(cart.getId());
        log.debug("购物车商品信息为：" + cartProductVOS);
        //遍历购物车商品数量判断库存是否足够
        for (CartProductVO cartProductVO : cartProductVOS) {
            if("1".equals(cartProductVO.getStatus())){
                //判断库存是否足够，如果不够则不能创建订单
                ProductQuery productQuery = new ProductQuery();
                productQuery.setId(cartProductVO.getProductId());
                //查询商品信息
                List<ProductVO> productVOS = productMapper.selectProduct(productQuery);
                log.debug("商品信息为：" + productVOS);
                if (productVOS.get(0).getStock() < cartProductVO.getQuantity()) {
                    throw new ServiceException(StatusCode.PRODUCT_NOT_ENOUGH);
                }
                log.debug("库存足够，可以创建订单");
                //计算订单总金额
                BigDecimal totalPrice = productVOS.get(0).getPrice().multiply(new BigDecimal(cartProductVO.getQuantity()));
                //创建订单
                Order order = new Order();
                order.setUserId(userId);

                order.setShippingAddressId(shippingAddressVO.getId());
                order.setProductsId(cartProductVO.getProductId());
                order.setProductName(productVOS.get(0).getProductName());
                //通过店铺id查询商铺名称
                ShopVO shopVO = shopMapper.selectShop(productVOS.get(0).getShopId());
                log.debug("查询店铺信息，shopVO={}", shopVO);
                order.setShopName(shopVO.getShopName());
                order.setProductsImg(productVOS.get(0).getProductImg());
                order.setProductsMsg(productVOS.get(0).getDescription());
                order.setPrice(totalPrice);
                order.setQuantity(cartProductVO.getQuantity());
                //设置订单状态
                order.setOrderStatus(OrderStatus.PENDING_PATD.getCode());
                //设置物流状态
                order.setShippingStatus(ShippingStatus.PICKED_UP.getCode());
                order.setCreateTime(new Date());
                //插入订单
                Integer insert = ordersMapper.insert(order);
                log.debug("插入订单条数结果为：" + insert);
                //更新商品库存
                productVOS.get(0).setStock(productVOS.get(0).getStock() - cartProductVO.getQuantity());
                productVOS.get(0).setUpdateTime(new Date());
                productMapper.update(productVOS.get(0));
                //删除购物车已购买的商品
                CartDeleteParam cartDeleteParam = new CartDeleteParam();
                cartDeleteParam.setCartId(cart.getId());
                cartDeleteParam.setProductId(cartProductVO.getProductId());
                cartMapper.deleteCartProducts(cartDeleteParam);
            }
        }
        //查询购物车商品
        cartProductVOS = cartMapper.selectCart(cart.getId());
        //如果购物车商品为空，则删除购物车
        if(cartProductVOS.isEmpty()){
            cartMapper.deleteCart(userId);
        }
        log.debug("订单创建成功");
    }

    /**
     * 通过用户id获取购物车信息
     * @param userId
     * @return
     */
    private Cart getCart(Long userId) {
        //查询购物车信息
        Cart cart = cartMapper.selectCartByUserId(userId);
        return cart;
    }
}
